﻿using Logistics.Manager;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Logistics
{
    public partial class frmSAPDataView : Form
    {
        ListViewColumnSorter lvwColumnSorter = new ListViewColumnSorter();
        private TC_OWI_FILE obj_tc_owi = new TC_OWI_FILE();
        private readonly TC_OWR_FILE _OWR_FILE;
        private List<Model.TC_OWR_FILE> OWRDatas;
        private List<Model.OwrStatus> owrStatus;
        private List<Model.OwrType> owrType;

        private List<string> owi;
        private string l_date;
        private string status;
        private string l_type;
        /// <summary>
        /// 用户所拥有的物流公司列表
        /// </summary>
        private List<Model.TC_OWI_FILE> user_owi_ulist;
        public frmSAPDataView()
        {
            InitializeComponent();
            this.listInfo.ListViewItemSorter = lvwColumnSorter;
            ImageList imgList = new ImageList();
            imgList.ImageSize = new Size(1, 20);//分别是宽和高
            listInfo.SmallImageList = imgList;
            _OWR_FILE = new TC_OWR_FILE();
            OWRDatas = new List<Model.TC_OWR_FILE>();
            owrStatus = new List<Model.OwrStatus>();
            owrType = new List<Model.OwrType>();
        }

        private void frmSAPDataView_Load(object sender, EventArgs e)
        {
            BindCmbData();
            dpDate.Value = DateTime.Now;
        }

        #region 绑定基础数据
        private void BindCmbData()
        {
            string l_user = MyForms.User.UserName;
            user_owi_ulist = obj_tc_owi.User_GetList(l_user);
            var tc_owi = new Model.TC_OWI_FILE();

            tc_owi.TC_OWI002 = "请选择";
            tc_owi.TC_OWI001 = null;
            user_owi_ulist.Insert(0, tc_owi);
            tc_owi_comb.DataSource = user_owi_ulist;
            tc_owi_comb.DisplayMember = "TC_OWI002";
            tc_owi_comb.ValueMember = "TC_OWI001";
            tc_owi_comb.SelectedIndex = 1;


            owrStatus.Add(new Model.OwrStatus { Id = null, Name = "请选择" });
            // owrStatus.Add(new Model.OwrStatus { Id = "0", Name = "0:开立" });
            owrStatus.Add(new Model.OwrStatus { Id = "1", Name = "1:导出未处理" });
            owrStatus.Add(new Model.OwrStatus { Id = "2", Name = "2:导出已处理" });
            owrStatus.Add(new Model.OwrStatus { Id = "3", Name = "3:回馈未处理" });
            owrStatus.Add(new Model.OwrStatus { Id = "4", Name = "4:回馈已处理" });
            owrStatus.Add(new Model.OwrStatus { Id = "5", Name = "5:不导物流" });
            // owrStatus.Add(new Model.OwrStatus { Id = "X", Name = "X:作废" });
            // owrStatus.Add(new Model.OwrStatus { Id = "D", Name = "D:WMS删除" });
            // owrStatus.Add(new Model.OwrStatus { Id = "F", Name = "F:WMS接收失败" });
            cmbStatus.DataSource = owrStatus;
            cmbStatus.DisplayMember = "Name";
            cmbStatus.ValueMember = "Id";
            cmbStatus.SelectedIndex = 0;


            owrType.Add(new Model.OwrType { Id = null, Name = "请选择" });
            owrType.Add(new Model.OwrType { Id = "11", Name = "11:出货单" });
            owrType.Add(new Model.OwrType { Id = "13", Name = "13:调拨出货" });
            owrType.Add(new Model.OwrType { Id = "14", Name = "14:两阶段拨出" });
            owrType.Add(new Model.OwrType { Id = "16", Name = "16:仓退出库" });
            owrType.Add(new Model.OwrType { Id = "17", Name = "17:库存调减单" });
            owrType.Add(new Model.OwrType { Id = "21", Name = "21:销退单" });
            owrType.Add(new Model.OwrType { Id = "2A", Name = "2A:拒收" });
            owrType.Add(new Model.OwrType { Id = "22", Name = "22:杂收单" });
            owrType.Add(new Model.OwrType { Id = "23", Name = "23:成品调拨拨入" });
            owrType.Add(new Model.OwrType { Id = "24", Name = "24:两阶段调拨拨入" });
            owrType.Add(new Model.OwrType { Id = "26", Name = "26:仓退入库" });
            owrType.Add(new Model.OwrType { Id = "27", Name = "27:库存调增单" });
            owrType.Add(new Model.OwrType { Id = "31", Name = "31:仓库转拨" });

            cmbtype.DataSource = owrType;
            cmbtype.DisplayMember = "Name";
            cmbtype.ValueMember = "Id";
            cmbtype.SelectedIndex = 0;

        }
        #endregion
        private void listInfo_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            if (e.Column == lvwColumnSorter.SortColumn)
            {
                if (lvwColumnSorter.Order == SortOrder.Ascending)
                {
                    lvwColumnSorter.Order = SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                lvwColumnSorter.SortColumn = e.Column;
                lvwColumnSorter.Order = SortOrder.Ascending;
            }
            this.listInfo.Sort();
        }
        private void AddListviewItem(Model.TC_OWR_FILE model)
        {
            ListViewItem item = null;
            item = new ListViewItem();
            var owr019 = owrStatus.FirstOrDefault(m => m.Id == model.TC_OWR019);
            item.Tag = model.TC_OWR001;
            item.Text = owr019?.Name;
            item.SubItems.Add(model.TC_OWR006?.ToString("yyyy-MM-dd"));
            var owr001 = owrType.FirstOrDefault(m => m.Id == model.TC_OWR001);
            item.SubItems.Add(owr001?.Name);
            item.SubItems.Add(model.TC_OWR002);
            item.SubItems.Add(model.TC_OWR003);
            item.SubItems.Add(model.TC_OWR004);
            item.SubItems.Add(model.TC_OWR005);
            item.SubItems.Add(model.TC_OWR007?.ToString("yyyy-MM-dd"));
            item.SubItems.Add(model.TC_OWR008?.ToString("yyyy-MM-dd"));
            item.SubItems.Add(model.TC_OWR009);
            item.SubItems.Add(model.TC_OWR010);
            item.SubItems.Add(model.TC_OWR0101);
            item.SubItems.Add(model.TC_OWR011 == "N" ? "否" : "是");
            item.SubItems.Add(model.TC_OWR012 == "N" ? "否" : "是");
            item.SubItems.Add(model.TC_OWR013);
            item.SubItems.Add(model.TC_OWR0131);
            item.SubItems.Add(model.TC_OWR0132);
            item.SubItems.Add(model.TC_OWR014);
            item.SubItems.Add(model.TC_OWR015);
            item.SubItems.Add(model.TC_OWR016);
            item.SubItems.Add(model.TC_OWR017);
            item.SubItems.Add(model.TC_OWR018);
            item.SubItems.Add(model.TC_OWR019);
            item.SubItems.Add(model.TC_OWR020?.ToString("yyyy-MM-dd"));
            item.SubItems.Add(model.TC_OWR021);
            item.SubItems.Add(model.TC_OWR022);

            this.listInfo.Items.Add(item);
        }

        private void butQuery_Click(object sender, EventArgs e)
        {
            if (this.objBGWorker.IsBusy)
            {
                return;
            }
            this.pbReport.Value = 0;
            this.pbReport.Text = "正在查询数据，请稍候...";
            this.pbReport.Maximum = 100;
            pbReport.Visible = true;
            if (tc_owi_comb.SelectedIndex > 0)
            {
                owi = new List<string>();
                owi.Add(tc_owi_comb.SelectedValue.ToString());
            }
            else
                owi = user_owi_ulist.Where(m => m.TC_OWI001 != null).Select(m => $"'{m.TC_OWI001}'").ToList();
            if (dpDate.LockUpdateChecked)
                l_date = dpDate.Value.ToString("yyyy-MM-dd");
            else
                l_date = null;
            if (cmbStatus.SelectedIndex > 0)
                status = cmbStatus.SelectedValue.ToString();
            else
                status = null;

            if (cmbtype.SelectedIndex > 0)
                l_type = cmbtype.SelectedValue.ToString();
            else
                l_type = null;

            this.objBGWorker.RunWorkerAsync();
        }

        private void butWMS_Click(object sender, EventArgs e)
        {
            /* if (listInfo.SelectedItems.Count == 0)
             {
                 MessageBox.Show("请选择物流信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                 return;
             }
             */

            if (tc_owi_comb.SelectedIndex > 0)
            {
                owi = new List<string>();
                owi.Add(tc_owi_comb.SelectedValue.ToString());
            }
            else
            {
                MessageBox.Show("请选择物流信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var tc_owr009 = owi[0].ToString();
            if (this.WMSBGWorker.IsBusy)
            {
                return;
            }
            FtpHelper.Instance.UserName = "eric";
            FtpHelper.Instance.Password = "topdaily";
            FtpHelper.Instance.FtpPath = "ftp://192.168.80.7";
            var _directoryPath = $"/WL_TEST/WMS/{tc_owr009}/RETURN/";
            var url = new Uri(FtpHelper.Instance.FtpPath + _directoryPath);
            var ftpFiles = FtpHelper.Instance.GetFileList(url);
            if (ftpFiles == null)
            {
                MessageBox.Show("未找到任何返回文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var files = ftpFiles.Where(m => m.EndsWith(".txt")).ToList();
            if (files.Count == 0)
            {
                MessageBox.Show("未找到任何返回文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                pbReport.Visible = true;
                this.pbReport.Value = 0;
                this.pbReport.Text = "正在处理数据，请稍候...";

                var model = new WMSModel { Files = files, tc_owr009 = tc_owr009, DirectoryPath = _directoryPath };
                this.WMSBGWorker.RunWorkerAsync(model);



            }
        }

        private void WMSBGWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var model = e.Argument as WMSModel;
                var downloadPath = Path.Combine(Application.StartupPath, $"LG\\WL_WORK\\{model.tc_owr009}\\RETURN");
                if (!Directory.Exists(downloadPath))
                    Directory.CreateDirectory(downloadPath);
                foreach (var item in model.Files)
                {
                    FtpHelper.Instance.Download(downloadPath, model.DirectoryPath, item);
                    var l_return_file = downloadPath + "\\" + item;
                    var lines = File.ReadAllLines(l_return_file).ToList();
                    this.pbReport.Maximum = lines.Count;
                    int i = 0;
                    foreach (string line in lines)
                    {
                        Console.WriteLine(line);
                        string[] array = line.Split(new char[] { ',' });

                        var l_tc_ows000 = array[0];
                        var l_tc_ows001 = array[1];
                        var l_tc_ows002 = array[2];
                        var l_tc_ows013 = array[13];
                        var l_tc_ows014 = array[14];
                        _OWR_FILE.OwsReturn(l_tc_ows000, l_tc_ows001, l_tc_ows002, l_tc_ows013, l_tc_ows014);
                        _OWR_FILE.OwrReturn(l_tc_ows000, l_tc_ows001);
                        i = i + 1;
                        WMSBGWorker.ReportProgress(i);
                    }
                    var filePath = Path.Combine(downloadPath, item);
                    if (File.Exists(filePath))
                        File.Delete(filePath);
                    FtpHelper.Instance.Delete(model.DirectoryPath, item);
                }
                Directory.Delete(downloadPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show("有返回文件，但处理失败，请联系管理员", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void WMSBGWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.pbReport.Value = e.ProgressPercentage;
        }

        private void WMSBGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("回馈成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.pbReport.Visible = false;
        }

        private void butWuLiu_Click(object sender, EventArgs e)
        {

        }

        private void butStatusChange_Click(object sender, EventArgs e)
        {
            if (tc_owi_comb.SelectedIndex > 0)
            {
                owi = new List<string>();
                owi.Add(tc_owi_comb.SelectedValue.ToString());
            }
            else
            {
                MessageBox.Show("请选择物流信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //检查状态
            var list = listInfo.CheckedItems;
            int i = 0;
            foreach (ListViewItem item in list)
            {
                i = i + 1;
                var l_tc_owr019 = Convert.ToString(item.SubItems[0].Text);
                l_tc_owr019 = l_tc_owr019.Substring(0, l_tc_owr019.IndexOf(":"));
                if ((l_tc_owr019 != "0") && (l_tc_owr019 != "1") && (l_tc_owr019 != "5"))
                {
                    MessageBox.Show("所选状态不为0、1、5,无法切换", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            if (i == 0)
            {
                MessageBox.Show("未勾选任何单据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var result = MessageBox.Show("确认保留底稿计算业绩，货物不从物流仓库出吗？请备注货物来源！", "审核框", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {

                list = listInfo.CheckedItems;

                foreach (ListViewItem item in list)
                {
                    var l_tc_owr001 = Convert.ToString(item.SubItems[2].Text);
                    l_tc_owr001 = l_tc_owr001.Substring(0, l_tc_owr001.IndexOf(":"));
                    var l_tc_owr002 = Convert.ToString(item.SubItems[3].Text);
                    var l_tc_owr019 = Convert.ToString(item.SubItems[0].Text);
                    l_tc_owr019 = l_tc_owr019.Substring(0, l_tc_owr019.IndexOf(":"));
                    _OWR_FILE.ChangeWuLiuStatus(l_tc_owr001, l_tc_owr002, l_tc_owr019);
                }
                MessageBox.Show("切换成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                butQuery_Click(sender, e);
            }





        }

        private void butDetail_Click(object sender, EventArgs e)
        {

            if (tc_owi_comb.SelectedIndex > 0)
            {
                owi = new List<string>();
                owi.Add(tc_owi_comb.SelectedValue.ToString());
            }
            else
            {
                MessageBox.Show("请选择物流信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //检查状态
            var list = listInfo.CheckedItems;
            int i = 0;
            foreach (ListViewItem item in list)
            {
                i = i + 1;

            }

            if (i > 1)
            {
                MessageBox.Show("查看单据明细无须选择,请直接选中单据查看明细", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var l_tc_owr001 = Convert.ToString(listInfo.SelectedItems[0].Tag);
            var l_tc_owr002 = Convert.ToString(listInfo.SelectedItems[0].SubItems[3].Text);
            var objDetail = new frmSAPDataDetail(l_tc_owr001, l_tc_owr002);
            objDetail.ShowDialog();

        }

        private void butExportStatus_Click(object sender, EventArgs e)
        {
            if (tc_owi_comb.SelectedIndex > 0)
            {
                owi = new List<string>();
                owi.Add(tc_owi_comb.SelectedValue.ToString());
            }
            else
            {
                MessageBox.Show("请选择物流信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            //检查状态
            var list = listInfo.CheckedItems;
            int i = 0;
            foreach (ListViewItem item in list)
            {
                i = i + 1;
                var l_tc_owr019 = Convert.ToString(item.SubItems[0].Text);
                l_tc_owr019 = l_tc_owr019.Substring(0, l_tc_owr019.IndexOf(":"));
                if (l_tc_owr019 != "2")
                {
                    MessageBox.Show("所选状态不为2,无法还原", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            if (i == 0)
            {
                MessageBox.Show("未勾选任何单据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var result = MessageBox.Show("是否确定还原单据？", "确定框", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {

                list = listInfo.CheckedItems;

                foreach (ListViewItem item in list)
                {
                    var l_tc_owr001 = Convert.ToString(item.SubItems[2].Text);
                    l_tc_owr001 = l_tc_owr001.Substring(0, l_tc_owr001.IndexOf(":"));
                    var l_tc_owr002 = Convert.ToString(item.SubItems[3].Text);
                    _OWR_FILE.ExportStatus(l_tc_owr001, l_tc_owr002);
                    butQuery_Click(sender, e);
                }
                MessageBox.Show("还原成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                butQuery_Click(sender, e);
            }

        }

        private void butKouZhang_Click(object sender, EventArgs e)
        {
            if (listInfo.SelectedItems.Count == 0)
            {
                MessageBox.Show("请选择物流信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var l_tc_owr019 = Convert.ToString(listInfo.SelectedItems[0].SubItems[22].Text);
            if (l_tc_owr019 == "3")
            {
                MessageBox.Show("扣帐失败，请联系管理员", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("物流未回馈，无法扣帐", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void objBGWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            objBGWorker.ReportProgress(50);
            OWRDatas = _OWR_FILE.GetList(owi, l_date, status, l_type);
            objBGWorker.ReportProgress(100);
        }

        private void objBGWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.pbReport.Value = e.ProgressPercentage;
        }

        private void objBGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            var query = OWRDatas.ToList();
            this.listInfo.Items.Clear();
            this.listInfo.BeginUpdate();
            foreach (var item in query)
            {
                AddListviewItem(item);
            }
            this.listInfo.EndUpdate();
            labCount.Text = query.Count().ToString();
            pbReport.Visible = false;
        }

        private void listInfo_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void buttonX1_Click(object sender, EventArgs e)
        {

        }

        private void sel_all_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listInfo.Items)
            {
                item.Checked = true;
            }

        }

        private void sel_non_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listInfo.Items)
            {
                item.Checked = false;
            }
        }

        private void sel_return_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listInfo.Items)
            {
                item.Checked = !item.Checked;
            }
        }

        private void CopyMenuItem_Click(object sender, EventArgs e)
        {
            if (this.listInfo.SelectedItems.Count == 0)
                return;
            var item = listInfo.SelectedItems[0];
            var str = new StringBuilder();
            str.AppendLine($"凭证种类：{item.Text}");
            str.AppendLine($"类型：{item.SubItems[1].Text}");
            str.AppendLine($"单据编号：{item.SubItems[2].Text}");
            str.AppendLine($"导出方：{item.SubItems[3].Text}");
            str.AppendLine($"送货方：{item.SubItems[4].Text}");
            str.AppendLine($"客户编号：{item.SubItems[5].Text}");
            str.AppendLine($"单据日期：{item.SubItems[6].Text}");
            str.AppendLine($"物流公司：{item.SubItems[7].Text}");
            str.AppendLine($"承送商：{item.SubItems[8].Text}");
            str.AppendLine($"备注：{item.SubItems[9].Text}");
            Clipboard.SetDataObject(str.ToString());
        }
    }

    public class WMSModel
    {
        public List<string> Files { get; set; }

        public string tc_owr009 { get; set; }

        public string DirectoryPath { get; set; }
    }
}
